package sql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import data.Season;

public class QueryDatabase {
	Connection connection;
	Season season = new Season();

	public QueryDatabase(Connection connection) {
		this.connection = connection;
	}

	public Season getlastSeason() {

		String getQuery = "SELECT* from sezoane";
		try {
			Statement getStatement = connection.createStatement();

			ResultSet rs = getStatement.executeQuery(getQuery);

			rs.last();
			season.setId(rs.getInt("id"));
			season.setName(rs.getString("name"));
			season.setEdition(rs.getString("edition"));
			season.setRoundsNumber(rs.getInt("roundsNumber"));
			season.setTeamsNumber(rs.getInt("teamsNumber"));
			season.setChampion(rs.getString("champion"));

		} catch (SQLException e) {
			e.printStackTrace();
			season = null;
		}

		return season;

	}

	public Season insertSeason(Season season) {
		String insertQuery = "INSERT INTO sezoane(name,edition,roundsNumber,teamsNumber,champion) values('$name','$edition',2,3,'$champion')";
		// String
		// insertQuery="INSERT INTO scoli (nume,strada,numar,oras,director,contabil) values('$nume','$strada',$numar,'$oras','$director','$contabil')";
		
String t=season.getName();
insertQuery=insertQuery.replace("$name",season.getName());
		insertQuery.replace("$edition", season.getEdition());
		insertQuery.replace("$roundsNumber", season.getRoundsNumber() + "");
		insertQuery.replace("$teamsNumber", season.getTeamsNumber() + "");
		insertQuery.replace("$champion", season.getChampion());

		try {
			Statement insertStatement = connection.createStatement();
			int result = insertStatement.executeUpdate(insertQuery);
			if (result == 1) {
				ResultSet rs = insertStatement.getGeneratedKeys();
				if (rs.next()) {
					season.setId(rs.getInt(1));
				}
			} else {
				season = null;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return season;
	}
}
